from pyxmpp2.streamevents import DisconnectedEvent
from pyxmpp2.message import Message 
from pyxmpp2.jid import JID
import logging
from pyxmpp2.interfaces import EventHandler, event_handler, QUIT
from pyxmpp2.streamevents import AuthorizedEvent
from pyxmpp2.client import Client
from pyxmpp2.interfaces import presence_stanza_handler, message_stanza_handler,XMPPFeatureHandler

logging.getLogger().setLevel(logging.INFO)
#logging.getLogger("pyxmpp2.tcp.out").setLevel(logging.DEBUG)
#logging.getLogger("pyxmpp2.tcp.in").setLevel(logging.DEBUG)

my_jid=JID('idb9a8ad72f1344a3ea1a111f2015dc8d2@localhost')
password='share5a0f80506ee705a14bcb16118a89f251'
jid_to = 'id0438c980b8e5ef0d77e8025b0880a696@localhost'
my_message='hello, i will go now'

from pyxmpp2.settings import XMPPSettings
settings = XMPPSettings({ "password": password,'port':5222,'server':'127.0.0.1' })

class MyHandler(EventHandler):
    @event_handler(AuthorizedEvent)
    def handle_authorized(self, event):
        message = Message(to_jid = jid_to,body = my_message)
        event.stream.send(message)
        #event.stream.disconnect()
        
    @event_handler()
    def handle_any_event(self, event):
        logging.info(u"Event:{0}".format(event))
        
             
    @event_handler(DisconnectedEvent)
    def handle_disconnected(self, event):
        return QUIT
        
    
class MsgHandler(XMPPFeatureHandler):
    @message_stanza_handler()
    def handle_message(self, stanza):
        logging.info(u"Msg: {0}".format(tostring(stanza.get_xml())))
        return None
        
from _thread import start_new_thread
import time
from xml.etree.ElementTree import tostring
def send_proc( handler1 ):
    message = Message(to_jid = jid_to,body = my_message)
    global client
    for i in range(5):
        c=input('enter...')
        client.send(message)
        logging.info(u"SEND: {0}".format(tostring(message.get_xml())))
    #client.disconnect()


h1 = MyHandler()
client = Client(my_jid, [ MsgHandler(),h1 ], settings)
client.connect()
start_new_thread( send_proc,(h1,) )
try:
    client.run()
except:
    client.disconnect()
